<template>
	<view class="reservation">
		<view class="card shop"
			@tap="$wanlshop.to(`/pages/service/select_shop_details?id=${storeId}&showSwitch=${true}`)">
			<view class="label-icon flex flex-middle">
				<uni-icons type="shop" color="#999" size="40rpx"></uni-icons>
				<view class="label ml5">预约门店</view>
			</view>
			<view class="shop-name flex flex-middle">
				<view>{{ storeName }}</view>
				<uni-icons type="right" color="#999" size="34rpx"></uni-icons>
			</view>
		</view>
		<view class="card time">
			<view class="label-icon">
				<view class="icon"></view>
				<view class="label">选择预约时间</view>
			</view>
			<view class="week">
				<view class="week-days" @tap="dayTimeChange(item)" :class="{
          prohibit: item.prohibit,
          active: dayTime === item.date
        }" v-for="item in weeks" :key="item.day">
					<view class="week-val font-bold">{{ item.weekday }}</view>
					<view class="day-val">{{ item.day }}</view>
				</view>
			</view>
			<view class="morning-afternoon">
				<view class="morning" :class="{ active: hoursType === 'forenoon' }" @tap="hoursTypeChange('forenoon')">
					{{ forenoon }}-11:59
				</view>
				<view class="afternoon" :class="{ active: hoursType !== 'forenoon' }"
					@tap="hoursTypeChange('afternoon')">
					12:00-{{ afternoon }}
				</view>
			</view>
			<view class="hours">
				<view class="hours-val" @tap="selectTime(item)" :class="{
          prohibit: item.prohibit,
          forbid: !item.available,
          active: time === item.time
        }" v-for="(item) in dayhours" :key="item.time">
					<view>{{ item.hhText }}</view>
					<text>{{ item.availableText }}</text>
				</view>
			</view>
		</view>
		<view class="card remark">
			<text class="title">备注</text>
			<textarea v-model="remarks" placeholder="选填，可输入您的其他要求" maxlength="30"></textarea>
			<text class="inputNum">{{remarks.length || 0}}/30</text>
		</view>
		<view class="card tips">
			<text class="title">预约通知</text>
			<rich-text :nodes="sub_desc"></rich-text>
		</view>
		<view class="footer">
			<button class="submit" @tap="submit">立即预约</button>
		</view>

	</view>
</template>

<script>
	let dataTme = (24 * 60 * 60 * 1000)
	export default {
		data() {
			return {
				storeId: '',
				orderGoodsId: '',

				storeName: '',
				storeId: '',
				storeAddress: '',


				timeList: [],
				// dayTimes:[],//时间列表
				// weeks:[],// 日期周列表
				// dayhours:[],//预约时间列表
				// 选择上午 或者下午
				hoursType: '', // forenoon afternoon 上午下午

				// 选择哪一天
				dayTime: '',

				// post params
				time: '', //预约时间
				remarks: '', //备注
				sub_desc: '', //预约须知

				// 今天
				nowWeekDay: new Date()
			}
		},
		computed: {
			weeks() { //周列表

				return this.timeList.map(item => {

					let now = Math.floor(new Date().getTime() / dataTme) * dataTme
					let old = Math.floor(new Date(item.date).getTime() / dataTme) * dataTme
					return {

						prohibit: old - now < 0,
						weekday: this.getWeekday(item.date),
						date: item.date,
						day: this.$wanlshop.timeFormat(new Date(item.date).getTime(), 'mm-dd')
					}
				})
			},
			weekTimeList() {
				return this.timeList.find(item => item.date === this.dayTime)?.slots || []
			},
			dayhours() {
				let slots = this.timeList.find(item => item.date === this.dayTime)?.slots || []
				let newData = slots.filter(item => {
					let time = this.$wanlshop.timeFormat(new Date(item.time).getTime(), 'hh')

					if (this.hoursType === 'forenoon') {
						return time < 12
					}
					return time > 12 || time === 12
				}).map(item => {
					let hhText = this.$wanlshop.timeFormat(item.time, 'hh:MM')
					return {
						...item,
						prohibit: this.isTimePast(item.time),
						availableText: item.available ? '可约' : '已满',
						hhText
					}
				})
				return newData
				// let slots = this.timeList.find(item=>item.date===this.dayTime)?.slots||[]
				// return slots.filter(item=>Number(this.$wanlshop.timeFormat(new Date(item.date).getTime(),'hh'))<12)
			},
			afternoon() {
				let slots = this.timeList.find(item => item.date === this.dayTime)?.slots || []
				let max = Math.max(...slots.map(item => item.time))
				return this.$wanlshop.timeFormat(new Date(max).getTime(), 'hh:MM')
			},
			forenoon() {
				let slots = this.timeList.find(item => item.date === this.dayTime)?.slots || []
				let min = Math.min(...slots.map(item => item.time))
				return this.$wanlshop.timeFormat(new Date(min).getTime(), 'hh:MM')
			}
		},
		onLoad(options) {
			let {
				storeId,
				orderGoodsId
			} = options
			this.getStoreDetail(storeId)
			this.storeId = storeId
			this.orderGoodsId = orderGoodsId
			this.hoursType = this.$wanlshop.timeFormat(new Date().getTime(), 'hh') < 12 ? 'forenoon' : 'afternoon'
		},
		onShow() {
			this.getTimeList(this.orderGoodsId)
		},
		methods: {
			async getStoreDetail(storeId) {
				let res = await this.$api.get({
					url: "/wanlshop/store/detail",
					data: {
						id: storeId,
					}
				})
				this.storeName = res.store_name || '';
				this.sub_desc = res.sub_desc;
			},
			submit() {
				if (this.time) {
					let data = {
						remarks: this.remarks,
						order_goods_id: this.orderGoodsId,
						booking_time: this.time
					};
					console.log('data', data)
					this.$api.post({
						url: '/wanlshop/booking/booking',
						data
					}).then(res => {
						// this.reservationStatus(this.orderId, this.orderGoodsId)
						uni.showToast({
							title: '预约成功',
							icon: 'none',
							mask: true,
							success: () => {
								setTimeout(() => {
									uni.navigateBack()
								}, 1000)
							}
						})
					})
				} else {
					uni.showToast({
						title: '请选择时间',
						icon: 'none'
					});
				}

			},
			isTimePast(time) {
				let now = Math.floor(new Date().getTime() / 1000)
				return new Date(time) < new Date(now)
				// let [hour, minute] = time.split(':')
				// const current = new Date();
				// const given = new Date();
				// given.setHours(hour);
				// given.setMinutes(minute);
				// return current >= given;
			},
			getWeekday(date) {
				const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
				const weekday = new Date(date).getDay();
				return weekdays[weekday];
			},
			hoursTypeChange(type) {
				this.hoursType = type
			},
			selectTime(data) {
				let {
					prohibit = false,
						available = 0,
						time = 0
				} = data

				console.log(data);
				if (!prohibit && available && time) {
					this.time = time
				}
			},
			async getTimeList(id) {
				this.timeList = await this.$api.get({
					url: '/wanlshop/booking/available',
					data: {
						order_goods_id: id,
						days: 7
					}
				})
				// this.timeList = res

				// this.weeks = res.map(item=>{
				//   return {
				//     day:this.$wanlshop.timeFormat(new Date(item.date).getTime(),'mm-dd')
				//   }
				// })
				console.log(this.weeks);

				let index = this.weeks.findIndex(item => {
					let now = Math.floor(new Date().getTime() / dataTme) * dataTme
					let old = Math.floor(new Date(`${item.date} 00:00`).getTime() / dataTme) * dataTme
					console.log(old, now);

					return old - now === 0
				})
				console.log(index, -123123123123);

				this.dayTime = this.weeks[index]?.date

				console.log(this.timeList);
				console.log(this.timeList.find(item => item.date === this.dayTime)?.slots || [])


				console.log(this.dayhours)
				// this.getDayhours()
			},
			dayTimeChange(item) {
				if (!item.prohibit) {
					this.dayTime = item.date
				}
			}
		}
	}
</script>

<style scoped lang="scss">
	.reservation {
		min-height: 100vh;
		background: $page-color-base;
		padding: 0 15rpx;
	}

	.card {
		background: #fff;
		border-radius: 10rpx;
		padding: 25rpx 15rpx;
		margin-bottom: 20rpx;
		position: relative;
		font-size: 26rpx;

		.inputNum {
			position: absolute;
			bottom: 15rpx;
			right: 30rpx;
			color: $font-color-dark;
		}

		textarea {
			width: 100%;
			height: 100rpx;
		}

		.title {
			margin-bottom: 12rpx;
		}
	}

	.footer {
		padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom);

		.submit {
			font-size: 28rpx;
			background-color: $theme;
			height: 80rpx;
			border-radius: 80rpx;
			line-height: 80rpx;
			width: 100%;
			text-align: center;
			color: #fff;
		}
	}


	.shop {
		display: flex;
		justify-content: space-between
	}

	.time {
		.week {
			display: flex;
			flex-wrap: wrap;
			padding: 20rpx 0;

			.week-days {
				flex: 1;
				text-align: center;
				border-radius: 10rpx;
				margin-right: 10rpx;
				padding: 10rpx 0;
				font-size: 26rpx;

				.week-val {
					font-size: 28rpx;
				}

				.day-val {
					font-size: 24rpx;
					color: $font-color-light;
				}

				&.prohibit {
					background: rgba(#ccc, 0.3);
					color: #ccc;
				}

				&.active {
					background: $theme;
					color: #fff;

					.day-val {
						color: #fff;
					}
				}

				&:last-child {
					margin-right: 0;
				}
			}
		}

		.morning-afternoon {
			display: flex;
			padding: 20rpx 0;
			margin-bottom: 20rpx;

			.morning,
			.afternoon {
				flex: 1;
				text-align: center;

				&.active {
					color: $theme;
				}
			}
		}

		.hours {
			display: flex;
			flex-wrap: wrap;
			justify-content: space-between;

			&::after {
				flex: 1;
				content: '';
			}

			.hours-val {
				width: calc(25% - 8rpx);
				text-align: center;
				height: 90rpx;
				display: flex;
				flex-direction: column;
				background: #f8f8f8;
				color: $font-color-base;
				border-radius: 10rpx;
				margin-bottom: 8rpx;
				margin-left: 8rpx;
				font-size: 26rpx;
				padding-top: 12rpx;

				text {
					font-size: 24rpx;
				}

				&.active {
					background: $bg-color-active;
					border: 2rpx solid $theme;
					color: $theme;
				}

				&.prohibit {
					background: rgba(#ccc, 0.3);
					color: #ccc;
				}

				&.forbid {
					text {
						color: red;
					}
				}
			}
		}
	}
</style>